import { getProfileAPI, loginAPI } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    profile: {}
  },
  mutations: {
    setToken(state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    removeToken(state) {
      state.token = null // 删除vuex中的token
      state.profile = {} // 清除用户信息
      removeToken() // 删除Cookie中的token
    },
    setProfile(state, profile) {
      state.profile = profile
    }
  },
  actions: {
    async login(ctx, data) {
      // 调用接口
      const { data: { token }} = await loginAPI(data)
      // 提交mutation
      ctx.commit('setToken', token)
    },
    async getProfile(ctx) {
      const res = await getProfileAPI()
      ctx.commit('setProfile', res.data)
      return res.data.permissions
    }
  }
}
